﻿using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace PlatformerCS
{
    /// <summary>
    /// An animation is bound to a game entity.
    /// It handles the entity spritesheet.
    /// </summary>
    public class Animation
    {
        // The entity the animation is bound to
        protected Entity entity;

        // Graphics
        protected Texture2D spriteSheet;
        protected Rectangle current;
        protected Point maxSize;
        protected int rate;
        protected int timer;
        protected float angle;

        public struct AnimInfo
        {
            public Texture2D Texture;
            public Rectangle Current;
            public Point MaxSize;
            public int Rate;
        }

        /// <summary>
        /// Gets the width of one frame.
        /// </summary>
        public int Width
        {
            get { return current.Width; }
        }

        /// <summary>
        /// Gets the height of one frame.
        /// </summary>
        public int Height
        {
            get { return current.Height; }
        }

        public Animation(Entity entity, AnimInfo info)
        {
            angle = 0;
            this.entity = entity;
            this.spriteSheet = info.Texture;
            this.current = info.Current;
            this.maxSize = info.MaxSize;
            this.rate = info.Rate;
        }

        /// <summary>
        /// Sets the current animation line on the spritesheet.
        /// </summary>
        public void SetAnimation(int n)
        {
            current.Y = n;
        }

        /// <summary>
        /// Updates the animation frames.
        /// </summary>
        public virtual void Update()
        {
            timer++;

            if (timer > rate)
            {
                current.X = (current.X + 1) % maxSize.X;
                timer = 0;
            }
        }

        /// <summary>
        /// Draws the current image of the spritesheet.
        /// </summary>
        /// <param name="spriteBatch">The spritebatch.</param>
        public void Draw(SpriteBatch spriteBatch)
        {
            Rectangle src = new Rectangle(current.X * current.Width, current.Y * current.Height, current.Width, current.Height);
//            spriteBatch.Draw(spriteSheet, entity.Position, src, Color.White);
            spriteBatch.Draw(spriteSheet, entity.Position, src, Color.White, angle, new Vector2(current.Width / 2, 0), 1f, SpriteEffects.FlipVertically, 0);
        }
    }
}
